import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
import type { File as FileData, FileQuery, FileList } from '../src/types/api/file'
import type { API } from '../src/types/api/response'

const Random = Mock.Random

// ------------ 常量定义 ------------
const fileTypes = [
  { ext: 'jpg', type: 'image/jpeg', prefix: '图片' },
  { ext: 'png', type: 'image/png', prefix: '图片' },
  { ext: 'pdf', type: 'application/pdf', prefix: '文档' },
  { ext: 'docx', type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', prefix: '文档' },
  { ext: 'xlsx', type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', prefix: '表格' },
  { ext: 'pptx', type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', prefix: '演示' },
  { ext: 'mp4', type: 'video/mp4', prefix: '视频' },
  { ext: 'mp3', type: 'audio/mpeg', prefix: '音频' },
  { ext: 'zip', type: 'application/zip', prefix: '压缩包' },
  { ext: 'txt', type: 'text/plain', prefix: '文本' }
]

const folders = ['文档', '图片', '视频', '音频', '下载', '工作', '个人', '项目', '其他']

// ------------ 工具函数 ------------
/**
 * 生成随机文件
 */
const generateRandomFile = (id: string): FileData => {
  const fileType = fileTypes[Math.floor(Math.random() * fileTypes.length)]
  const fileName = `${fileType.prefix}_${Random.word(3, 8)}.${fileType.ext}`
  const originalName = `${Random.cword(2, 5)}.${fileType.ext}`
  const size = Random.integer(1024, 10485760) // 1KB 到 10MB
  const folder = folders[Math.floor(Math.random() * folders.length)]
  const path = `/uploads/${Random.date('yyyy/MM/dd')}/${fileName}`
  const uploadTime = Random.datetime('yyyy-MM-dd HH:mm:ss')
  const hasUpdate = Math.random() < 0.3
  const uploaders = ['admin', 'user1', 'user2', 'user3']
  const uploader = uploaders[Math.floor(Math.random() * uploaders.length)]
  
  return {
    id,
    name: fileName,
    originalName,
    type: fileType.type,
    size,
    path,
    url: `http://localhost:3000${path}`,
    folder,
    description: Random.csentence(5, 20),
    uploadTime,
    uploadBy: uploader,
    updateTime: hasUpdate ? Random.datetime('yyyy-MM-dd HH:mm:ss') : undefined,
    updateBy: hasUpdate ? uploaders[Math.floor(Math.random() * uploaders.length)] : undefined
  }
}

// ------------ 模拟数据 ------------
const files: FileData[] = Array.from({ length: 50 }, (_, index) => 
  generateRandomFile(String(index + 1))
)

// ------------ API 实现 ------------
/**
 * 获取文件列表
 */
const getFileListApi: MockMethod = {
  url: '/api/file/list',
  method: 'get',
  response: ({ query }: { query: FileQuery }): API.Response<FileList> => {
    
    const { keyword, fileType, page = 1, pageSize = 10 } = query
    
    // 确保 page 和 pageSize 是数字类型
    const pageNum = Number(page)
    const pageSizeNum = Number(pageSize)
    
    let filteredFiles = [...files]

    if (keyword) {
      filteredFiles = filteredFiles.filter(
        file => file.name.includes(keyword) || file.description?.includes(keyword)
      )
    }

    if (fileType) {
      filteredFiles = filteredFiles.filter(file => file.type === fileType)
    }

    const startIndex = (pageNum - 1) * pageSizeNum
    const endIndex = startIndex + pageSizeNum
    const list = filteredFiles.slice(startIndex, endIndex)

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        list,
        total: filteredFiles.length
      }
    }
  }
}

/**
 * 上传文件
 */
const uploadFileApi: MockMethod = {
  url: '/api/file/upload',
  method: 'post',
  response: ({ body }: { body: { ids?: string[], folderId?: string, file?: File, folder?: string, description?: string } }): API.Response<FileData | null> => {
    const file: FileData = {
      id: String(files.length + 1),
      name: body.file?.name || '',
      originalName: body.file?.name || '',
      type: body.file?.type || '',
      size: body.file?.size || 0,
      path: `/uploads/2024/03/10/${body.file?.name || ''}`,
      url: `http://localhost:3000/uploads/2024/03/10/${body.file?.name || ''}`,
      folder: body.folder,
      description: body.description,
      uploadTime: new Date().toISOString(),
      uploadBy: 'admin',
      updateTime: undefined,
      updateBy: undefined
    }
    files.push(file)
    return {
      code: 200,
      success: true,
      message: '上传成功',
      data: file
    }
  }
}

/**
 * 删除文件
 */
const deleteFileApi: MockMethod = {
  url: '/api/file',
  method: 'delete',
  response: ({ body }: { body: { ids?: string[], folderId?: string } }): API.Response<null> => {
    const { ids = [] } = body
    ids.forEach(id => {
      const index = files.findIndex(file => file.id === id)
      if (index > -1) {
        files.splice(index, 1)
      }
    })
    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

/**
 * 获取文件详情
 */
const getFileDetailApi: MockMethod = {
  url: '/api/file/:id',
  method: 'get',
  response: ({ params }: { params: { id: string } }): API.Response<FileData | null> => {
    const file = files.find(item => item.id === params.id)
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: file || null
    }
  }
}

/**
 * 更新文件信息
 */
const updateFileApi: MockMethod = {
  url: '/api/file/:id',
  method: 'put',
  response: ({ params, body }: { params: { id: string }; body: Partial<FileData> }): API.Response<null> => {
    const index = files.findIndex(file => file.id === params.id)
    if (index > -1) {
      files[index] = {
        ...files[index],
        ...body,
        updateTime: new Date().toISOString(),
        updateBy: 'admin'
      }
    }
    return {
      code: 200,
      success: true,
      message: '更新成功',
      data: null
    }
  }
}

/**
 * 移动文件
 */
const moveFileApi: MockMethod = {
  url: '/api/file/move',
  method: 'put',
  response: ({ body }: { body: { ids?: string[], folderId?: string } }): API.Response<null> => {
    const { ids = [], folderId } = body
    ids.forEach(id => {
      const file = files.find(item => item.id === id)
      if (file) {
        file.folder = folderId
        file.updateTime = new Date().toISOString()
        file.updateBy = 'admin'
      }
    })
    return {
      code: 200,
      success: true,
      message: '移动成功',
      data: null
    }
  }
}

/**
 * 复制文件
 */
const copyFileApi: MockMethod = {
  url: '/api/file/copy',
  method: 'post',
  response: ({ body }: { body: { ids?: string[], folderId?: string } }): API.Response<FileData | null> => {
    const { ids = [], folderId } = body
    const newFiles: FileData[] = []
    ids.forEach(id => {
      const file = files.find(item => item.id === id)
      if (file) {
        const newFile: FileData = {
          ...file,
          id: String(files.length + 1),
          folder: folderId,
          uploadTime: new Date().toISOString(),
          uploadBy: 'admin',
          updateTime: undefined,
          updateBy: undefined
        }
        files.push(newFile)
        newFiles.push(newFile)
      }
    })
    return {
      code: 200,
      success: true,
      message: '复制成功',
      data: newFiles[0] || null
    }
  }
}

/**
 * 预览文件
 */
const previewFileApi: MockMethod = {
  url: '/api/file/:id/preview',
  method: 'get',
  response: ({ params }: { params: { id: string } }): API.Response<FileData | null> => {
    const file = files.find(item => item.id === params.id)
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: file || null
    }
  }
}

/**
 * 下载文件
 */
const downloadFileApi: MockMethod = {
  url: '/api/file/:id/download',
  method: 'get',
  response: ({ params }: { params: { id: string } }): API.Response<FileData | null> => {
    const file = files.find(item => item.id === params.id)
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: file || null
    }
  }
}

// ------------ 导出 ------------
export default [
  getFileListApi,
  uploadFileApi,
  deleteFileApi,
  getFileDetailApi,
  updateFileApi,
  moveFileApi,
  copyFileApi,
  previewFileApi,
  downloadFileApi
] as MockMethod[] 